﻿using System.Text;
using System.Text.Json.Serialization;
using System.Xml;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using net.xBei.Filters;
using net.xBei.WebApi.Filters;

namespace net.xBei.WebApi.FrameworkExtensions {
    /// <summary>
    /// 
    /// </summary>
    public static class MvcExtensions {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection SetupMvc(this IServiceCollection services) {
            services.AddControllers(option => {
                option.Filters.Add<ValidationFilter>();
                //暂时禁用
                //option.Filters.Add<ExceptionFilterAttribute>();
            })
                .AddJsonOptions(options => {
                    //options.JsonSerializerOptions.IgnoreNullValues = true;
                    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                });
            services.AddMvc()
                    .AddMvcOptions(options => {
                        options.Filters.AddService<ObsoleteActionFilter>();
                        options.InputFormatters.Add(new TextPlainInputFormatter());
                        options.OutputFormatters.Add(new XmlSerializerOutputFormatter(new XmlWriterSettings { Encoding = Encoding.UTF8 }));
                    });
            services.AddSingleton<ObsoleteActionFilter>();
            return services;
        }
    }
}
